package com.aids_malaria.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.aids_malaria.R;
import com.aids_malaria.app.AppManager;
import com.aids_malaria.app.Constant;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.NetWorkUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.LoadingDialog;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity implements TitleBar.OnTitleBarClickListener {

    protected Activity mActivity;
    protected Context mContext;
    protected Unbinder mUnbinder;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        mUnbinder = ButterKnife.bind(this);
        mActivity = this;
        mContext = this;
        RxBus.getDefault().register(mContext);
        LogUtil.d("activity:------------" + getComponentName().getClassName());
        AppManager.getInstance().addActivity(this);
        initView();
        initData();
        initLinkStatus();

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkLink();
    }

    /**
     * 检查是否连通
     */
    public void checkLink(){
        String padId = AppUtil.getDeviceId(mContext);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).checkLink(padId)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>(){

                    @Override
                    protected void onStart() {

                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        SpUtil.putBoolean(mContext,Constant.IS_LINK_SUCCESS,true);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        super.onError(message);
                        SpUtil.putBoolean(mContext,Constant.IS_LINK_SUCCESS,false);
                    }

                    @Override
                    protected void onFinish() {
                        initLinkStatus();
                    }
                });
    }

    public LoadingDialog getLoadingDialog(){
        if (loadingDialog == null){
            loadingDialog = new LoadingDialog(this);
        }
        return loadingDialog;
    }

    protected abstract int getLayoutId();

    protected void initView(){

    }

    protected void initData(){

    }

    /**
     * 初始化连接状态
     */
    protected void initLinkStatus(){
        try{
            ImageView iv_link_one = findViewById(R.id.iv_link_one);
            ImageView iv_link_two = findViewById(R.id.iv_link_two);
            if (iv_link_one == null || iv_link_two == null){return;}
            if(isOnLine()){
                iv_link_one.setBackgroundColor(Color.GREEN);
                iv_link_two.setBackgroundColor(Color.GREEN);
            }else{
                iv_link_one.setBackgroundColor(Color.RED);
                iv_link_two.setBackgroundColor(Color.RED);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 是否在线状态(在线工作模式以及连接成功)
     * @return
     */
    protected boolean isOnLine(){
        if(!NetWorkUtil.isConnected(mContext) || !NetWorkUtil.isNetworkConnected(mContext)){
            return false;
        }else{
            return SpUtil.getBoolean(mContext, Constant.IS_WORK_MODEL_ON_LINE,true) &&
                    SpUtil.getBoolean(mContext, Constant.IS_LINK_SUCCESS,false);
        }
    }

    /**
     * 初始化titlebar
     * @param titleBar
     * @param title
     */
    public void initTitleBar(TitleBar titleBar, String title){
        initTitleBar(titleBar, title, false);
    }

    /**
     * 初始化titlebar
     * @param titleBar
     * @param title
     */
    public void initTitleBar(TitleBar titleBar, String title, boolean isShowGone){
        titleBar.setmOnTitleBarClickListener(this);
        if(isShowGone){
            titleBar.setBackGone();
        }
        titleBar.setTitle(title);
    }

    /**
     * 跳转页面
     *
     * @param cls
     */
    public void startActivity(Class cls) {
        startActivity(cls, null);
    }

    /**
     * 跳转页面,带参数
     *
     * @param cls
     */
    public void startActivity(Class cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityForResult(Class cls,int requestCode ,Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent,requestCode);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                View v = getCurrentFocus();
                if (isShouldHideKeyboard(v, ev)) {
                    hideKeyBord();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 隐藏键盘
     */
    public void hideKeyBord() {
        //点击空白位置 隐藏软键盘
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService
                (INPUT_METHOD_SERVICE);
        boolean hideSoftInputFromWindow = mInputMethodManager.hideSoftInputFromWindow(this
                .getCurrentFocus().getWindowToken(), 0);
    }

    @Override
    public void back() {
//        AppManager.getInstance().finishActivity();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(mContext);
    }

    /**
     * 连接事件回调
     * @param linkEvent
     */
    @Subscribe
    public void onCodeEvent(Events.LinkEvent linkEvent){
        initLinkStatus();
    }

    /**
     * 连接失败事件回调，隐藏loading框
     * @param connectError
     */
    @Subscribe
    public void onCodeEvent(Events.ConnectError connectError){
        getLoadingDialog().dismiss();
    }

}
